AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
include("shared.lua")
-- Models
--Asteroids
resource.AddFile( "models/asteroid1.mdl")
resource.AddFile( "models/asteroid2.mdl")
resource.AddFile( "models/asteroid3.mdl")
resource.AddFile( "models/asteroid4.mdl")
resource.AddFile( "models/asteroid5.mdl")
-- Ship
resource.AddFile( "models/as_ship/as_ship.mdl")
resource.AddFile( "models/as_ship/as_ship_gib1.mdl")
resource.AddFile( "models/as_ship/as_ship_gib2.mdl")
resource.AddFile( "models/as_ship/as_ship_gib3.mdl")
--Machine
resource.AddFile( "models/johny-srka/arcade_machine_static.mdl")

-- Materials
--Ship
resource.AddFile( "materials/models/as_ship/fluorescentwhite001a.vmt")
resource.AddFile( "materials/models/as_ship/metalstainless01.vmt")
resource.AddFile( "materials/models/as_ship/metalwall076a.vmt")
--Asteroids
resource.AddFile( "materials/models/asteroids/rockwall010b.vmt")
--Machine
resource.AddFile( "materials/models/johny-srka/defender.vmt" )
--Skybox
resource.AddFile( "materials/skybox/sky_starfield01.vtf")
resource.AddFile( "materials/skybox/sky_stars01bk.vmt")
resource.AddFile( "materials/skybox/sky_stars01dn.vmt")
resource.AddFile( "materials/skybox/sky_stars01ft.vmt")
resource.AddFile( "materials/skybox/sky_stars01lf.vmt")
resource.AddFile( "materials/skybox/sky_stars01rt.vmt")
resource.AddFile( "materials/skybox/sky_stars01up.vmt")

-- Sound
resource.AddFile( "sound/as_death.wav" )
resource.AddFile( "sound/as_music.wav" )
resource.AddFile( "sound/as_ship_fire.wav" )
resource.AddFile( "sound/as_thrust.wav" )

-- Map
resource.AddFile( "maps/" .. game.GetMap() .. ".bsp" );



local BASE_ASTEROIDS = 5
local MAX_ASTEROIDS = 5
WorldBox = "place holder"
HighScores = {}


function GM:GetGameDescription()
	
	return "asteroids"
	
end

function GM:SetupPlayerVisibility( ply, viewent )
	if !(viewent == ply) then
		if ValidEntity(ply.ship) then
			AddOriginToPVS( ply.ship:GetPos())
			AddOriginToPVS( ply:GetPos())	
		end
	end
end

function GM:ShowTeam(ply)
	umsg.Start("showScores", ply) 
	umsg.End()
end

function GM:ShowHelp( ply)
	umsg.Start("joinMsg", ply) 
	umsg.End()
end

function GM:InitPostEntity()
	physSettings = {}
	physSettings.MaxVelocity = 12000
	physenv.SetPerformanceSettings(physSettings)
	for k,v in pairs(ents.GetAll()) do
		if v:GetName() == "world_edges" then
			WorldBox = v
		end
	end
end

function longTermAd( ply )
	timer.Simple(9, 
		function() 
			if ValidEntity(ply) then
				if !ply.IsUsing then 
					ply:ChatPrint("Press USE on any Machine to start the game") 
				end 
				longTermAd(ply) 
			end
		end)
end

function GM:PlayerInitialSpawn(ply)

	umsg.Start("joinMsg", ply)
	umsg.End()
	
end

function GM:PlayerSpawn( ply )
	timer.Simple(2, function() ply:ChatPrint("Press USE on any Machine to start the game") end )
	longTermAd(ply)
	ply:StripWeapons()
end


local function MakeAsteroids()

	MAX_ASTEROIDS = table.Count(player.GetHumans()) * 5
	
	local Asteroids = ents.FindByClass("asteroid")
	
	if table.Count(Asteroids) < BASE_ASTEROIDS + MAX_ASTEROIDS then
		
		local asSpawns = ents.FindByName("asteroid_spawn")
		
		if table.Count(asSpawns) < 1 then return end
		
		local newAsteroid = ents.Create("asteroid")
		
		newAsteroid:SetPos(asSpawns[math.random(1,table.Count(asSpawns))]:GetPos())
		newAsteroid:Spawn()
		local rndDir = Vector(math.Rand(-1,1), math.Rand(-1,1),math.Rand(-1,1))
		newAsteroid:GetPhysicsObject():SetVelocity( rndDir * math.random(800,900))
		
		timer.Simple(math.random(5,10), MakeAsteroids)
	else
		timer.Simple(5, MakeAsteroids)
	end
end
timer.Simple(math.random(5,10), MakeAsteroids)


function cleanScoreTable()

	for k, v in pairs(HighScores) do
		if (v[1] == nil or
		   v[2] == nil) or
		   (v[1] == "") then
			table.remove(HighScores, k)
		end
	end
		
end

function showScores(ply, cmd, args)

	table.SortByMember(HighScores, 2)
	
	for k,v in pairs(HighScores) do
		
		ply:ChatPrint("#" .. tostring(k) .. " - " .. v[1] .. " - " .. tostring(v[2]) .. " Points.")
		
	end

end
concommand.Add("showScores", showScores)

function LogScore( ply )

	if ply.score <= 0 then return end
	ply.score = math.Round(ply.score)
	local winDex = 0
	local winVal = 0
	
	print("Unsorted Scores")
	PrintTable(HighScores)
	table.SortByMember(HighScores, 2)
	print("Sorted Scores")
	PrintTable(HighScores)
	
	for k,v in pairs(HighScores) do
		if v[2] > winVal then
			if ply.score > v[2] then
				winDex = k
				winVal = v[2]
			end
		end
	end
	if winDex > 0 then
		table.insert(HighScores, winDex, {ply:Nick(), ply.score})
		--ply:ChatPrint("Congratulations, " .. ply:Nick() .. "!! You got a new high score!!")
		--ply:ChatPrint("#" .. tostring(winDex) .. " - " .. ply:Nick() .. " - " .. tostring(ply.score) .. " Points.")
		while table.Count(HighScores) > MAX_SCORES do
			table.remove(HighScores)
		end
		SaveHighScores()
		umsg.Start("showScores", ply) 
			umsg.Long(winDex)
		umsg.End()
	else
		if table.Count(HighScores) < MAX_SCORES then
			winDex = table.insert(HighScores, {ply:Nick(), ply.score})
			--ply:ChatPrint("Congratulations, " .. ply:Nick() .. "!! You got a new high score!!")
			--ply:ChatPrint("#" .. tostring(winDex) .. " - " .. ply:Nick() .. " - " .. tostring(ply.score) .. " Points.")
		end
		SaveHighScores()
		umsg.Start("showScores", ply) 
			umsg.Long(winDex)
		umsg.End()
	end
	
end

function getScores(ply, cmd, args)

	table.SortByMember(HighScores, 2)
	if table.Count(HighScores) > 0 then
	
		for k,v in pairs(HighScores) do
			
			umsg.Start("scores", ply)
				if k == 1 then
					umsg.Bool(true)
				else
					umsg.Bool(false)
				end
				umsg.String(v[1])
				umsg.Long(v[2])
			umsg.End()
		
		end
	end
end
concommand.Add("get_scores", getScores)

function SaveHighScores()
	
	local strScoreSave = ""

	table.SortByMember(HighScores, 2)
	
	for k,v in pairs(HighScores) do
		strScoreSave = strScoreSave .. v[1] .. "," .. v[2] .. "\n"
	end
	file.Write("asteroid_scores.txt", strScoreSave)
	
end

function resetHighScores(ply, cmd, args)
	
	if !ply:IsAdmin() then 
		ply:ChatPrint("Must Be Admin to use that command")
		return 
	end
	local strScoreSave = ""
	
	HighScores = {{ "High Score", 500000 }, { "Ok Score", 100000 } ,{ "Low Score", 10000 }}
	
	table.SortByMember(HighScores,2)
	
	for k,v in pairs(HighScores) do
		strScoreSave = strScoreSave .. v[1] .. "," .. v[2] .. "\n"
	end
	file.Write("asteroid_scores.txt", strScoreSave)
	
end
concommand.Add("as_reset_high_scores", resetHighScores)

function LoadHighScores()

	if file.Exists("asteroid_scores.txt") then
		local scoreRead = file.Read("asteroid_scores.txt")
		local readTemp = string.Explode("\n", scoreRead)
		HighScores = {}
		for k,v in pairs(readTemp) do
			local nI = table.insert(HighScores, string.Explode(",", v))
			HighScores[nI][2] = tonumber(HighScores[nI][2])
		end
	else
		HighScores = {{ "High Score", 500000 }, { "Ok Score", 100000 } ,{ "Low Score", 10000 }}
	end
	cleanScoreTable()
end
LoadHighScores()

